package com.peng.leetcode.array;

import java.util.*;

/**
 * CombinationSum2
 * 40. 组合总和 II
 * https://leetcode.cn/problems/combination-sum-ii/
 *
 * @author: lupeng6
 * @create: 2023/2/19 19:04
 */
public class CombinationSum2 {

    private List<List<Integer>> ans = new ArrayList<>();
    private Set<Integer> set = new HashSet<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return null;
        }
        for (int i = 0; i < candidates.length; i++) {
            ArrayDeque<Integer> q = new ArrayDeque<>();
            q.offerLast(candidates[i]);
            backtrack(candidates, target, i, candidates[i], q);
        }
        return ans;
    }

    private void backtrack(int[] candidates, int target, int index, int sum, ArrayDeque<Integer> q) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            ans.add(new ArrayList<>(q));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (set.contains(candidates[i])) {
                continue;
            }
            q.offerLast(candidates[i]);
            set.add(candidates[i]);
            backtrack(candidates, target, i + 1, sum + candidates[i], q);
            q.pollLast();
            set.remove(candidates[i]);
        }
    }
}
